/**
 * 用户相关的处理函数，供路由模块调用
 */

const jwt = require('jsonwebtoken')

/************************ 引入自定义模块 *************************/
const db = require('../utils/mysqlUtils')
const { getSalt, md5WithSalt } = require('../utils/encryptionUtils')

const constants = require('../config/constants')
const rescode = require('../config/rescode')

// 用户注册处理
module.exports.reg = (req, res) => {
  // 验证用户名在数据库中是否已存在
  const sql1 = "select * from sys_user where username = ?"
  db.query(sql1, req.body.username, (err1, results1) => {
    if (err1) {
      return res.r(err1.message, rescode.DB_HANDLER_ERROR)
    }

    if (results1.length > 0) {
      return res.r('用户名已注册', rescode.COMMON_ERROR)
    }
  })

  // 获取随机盐值
  const salt = getSalt(16)
  req.body.salt = salt
  req.body.password = md5WithSalt(req.body.password, salt)

  // 向数据库中插入数据 
  const sql2 = "insert into sys_user set ?"
  db.query(sql2, req.body, (err2, results2) => {
    if (err2) {
      return res.r(err2.message, rescode.DB_HANDLER_ERROR)
    }

    // SQL 插入语句执行成功，但影响行数不为 1
    if (results2.affectedRows !== 1) {
      return res.r("注册失败，请稍后重试", rescode.DB_RUN_ERROR)
    }

    return res.r("注册成功")
  })
}

// 用户登录处理
module.exports.login = (req, res) => {
  // 验证用户名在数据库中是否存在
  const sql1 = "select * from sys_user where username = ?"
  db.query(sql1, req.body.username, (err, results) => {
    if (err) {
      return res.r(err.message, rescode.DB_HANDLER_ERROR)
    }

    // 验证是否存在指定用户名的用户
    if (results.length !== 1) {
      return res.r('用户名不存在', rescode.COMMON_ERROR)
    }

    // 校验密码是否正确
    if (md5WithSalt(req.body.password, results[0].salt) != results[0].password) {
      return res.r('密码输入不正确', rescode.COMMON_ERROR)
    }

    // 剔除用户信息的私密信息 password 和 salt
    const userInfo = { ...results[0] }
    delete userInfo.password
    delete userInfo.salt

    // 生成token
    const token = jwt.sign(userInfo, constants.TOKEN_SECRET_KEY, { expiresIn: constants.TOKEN_EXPIRES_TIME })

    // 返回数据
    return res.r({ userInfo, token })
  })
}

// 处理获取个人信息
module.exports.profile = (req, res) => {
  const sql = "select * from sys_user where id = ?"
  db.query(sql, req.auth.id, (err, results) => {
    if (err) {
      return res.r(err.message, rescode.DB_HANDLER_ERROR)
    }

    // 验证编号是否存在
    if (results.length !== 1) {
      return res.r('用户不存在', rescode.COMMON_ERROR)
    }

    // 剔除用户信息的私密信息 password 和 salt
    const userInfo = { ...results[0] }
    delete userInfo.password
    delete userInfo.salt

    // 返回数据
    return res.r(userInfo)
  })
}

// 处理通过ID查询个人信息
module.exports.getById = (req, res) => {
  const sql = "select * from sys_user where id = ?"
  db.query(sql, req.params.id, (err, results) => {
    if (err) {
      return res.r(err.message, rescode.DB_HANDLER_ERROR)
    }

    // 验证编号是否存在
    if (results.length !== 1) {
      return res.r('用户不存在', rescode.COMMON_ERROR)
    }

    // 剔除用户信息的私密信息 password 和 salt
    const userInfo = { ...results[0] }
    delete userInfo.password
    delete userInfo.salt

    // 返回数据
    return res.r(userInfo)
  })
}

// 处理通过分页查询查询个人信息
module.exports.getPageList = (req, res) => {
  let sql1 = "select count(1) total from sys_user where 1 = 1"
  let sql2 = "select id, username, phone, email, age, gender, birth, avatar, created_time from sys_user where 1 = 1"

  let params = [] // 实参
  if (req.query.username) {
    sql1 += " and username like ?"
    sql2 += " and username like ?"
    params.push(req.query.username + '%')
  }

  if (req.query.phone) {
    sql1 += " and phone like ?"
    sql2 += " and phone like ?"
    params.push(req.query.phone + '%')
  }

  db.query(sql1, params, (err1, results1) => {
    if (err1) {
      return res.r(err1.message, rescode.DB_HANDLER_ERROR)
    }

    if (results1.length === 0) {
      return res.r({ total: 0, users: [] })
    }

    sql2 += " order by id desc limit ?, ?"
    params.push(+(req.query.pageNo - 1) * req.query.pageSize, +req.query.pageSize)
    db.query(sql2, params, (err2, results2) => {
      if (err2) {
        return res.r(err2.message, rescode.DB_HANDLER_ERROR)
      }

      // 返回数据
      return res.r({ total: results1[0].total, users: results2 })
    })
  })
}

// 处理修改个人信息
module.exports.bindPhone = (req, res) => {
  const id = req.auth.id
  const phone = req.body.phone

  const sql1 = "select * from sys_user where phone = ? and id != ?"
  db.query(sql1, [phone, id], (err1, results1) => {
    if (err1) {
      return res.r(err1.message, rescode.DB_HANDLER_ERROR)
    }

    // 验证手机号是否已被绑定
    if (results1.length > 0) {
      return res.r('手机号已被使用', rescode.COMMON_ERROR)
    }

    const sql2 = "update sys_user set phone = ?, updated_time = now() where id = ?"
    db.query(sql2, [phone, id], (err2, results2) => {
      if (err2) {
        return res.r(err2.message, rescode.DB_HANDLER_ERROR)
      }

      // 验证手机号是否已被绑定
      if (results2.affectedRows !== 1) {
        return res.r('绑定失败', rescode.COMMON_ERROR)
      }
      // 返回数据
      return res.r()
    })
  })
}

// 处理修改个人信息
module.exports.bindEmail = (req, res) => {
  const id = req.auth.id
  const email = req.body.email

  const sql1 = "select * from sys_user where email = ? and id != ?"
  db.query(sql1, [email, id], (err1, results1) => {
    if (err1) {
      return res.r(err1.message, rescode.DB_HANDLER_ERROR)
    }

    // 验证手机号是否已被绑定
    if (results1.length > 0) {
      return res.r('邮箱已被使用', rescode.COMMON_ERROR)
    }

    const sql2 = "update sys_user set email = ?, updated_time = now() where id = ?"
    db.query(sql2, [email, id], (err2, results2) => {
      if (err2) {
        return res.r(err2.message, rescode.DB_HANDLER_ERROR)
      }

      // 验证手机号是否已被绑定
      if (results2.affectedRows !== 1) {
        return res.r('绑定失败', rescode.COMMON_ERROR)
      }
      // 返回数据
      return res.r()
    })
  })
}

// 处理修改个人信息
module.exports.modify = (req, res) => {
  if (req.body.phone) {
    req.body.delete.phone
  }
  if (req.body.email) {
    req.body.delete.email
  }

  const sql = "update sys_user set ? where id = ?"
  console.log(req.body)
  db.query(sql, [req.body, req.body.id], (err, results) => {
    if (err) {
      return res.r(err.message, rescode.DB_HANDLER_ERROR)
    }
    console.log(results)
    // 验证编号是否存在
    if (results.affectedRows !== 1) {
      return res.r('修改失败', rescode.COMMON_ERROR)
    }

    // 返回数据
    return res.r()
  })
}

// 处理删除个人信息
module.exports.delete = (req, res) => {
  const sql = "delete from sys_user where id = ?"
  db.query(sql, req.params.id, (err, results) => {
    if (err) {
      return res.r(err.message, rescode.DB_HANDLER_ERROR)
    }

    // 验证编号是否存在
    if (results.affectedRows !== 1) {
      return res.r('删除失败', rescode.COMMON_ERROR)
    }

    // 返回数据
    return res.r()
  })
}